package com.pussinboots.morning.cms.modules.goods.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pussinboots.morning.cms.common.security.AuthorizingUser;
import com.pussinboots.morning.cms.common.util.ResultBean;
import com.pussinboots.morning.cms.common.util.SingletonLoginUtils;
import com.pussinboots.morning.cms.modules.system.category.entity.OsCategory;
import com.pussinboots.morning.cms.modules.system.category.service.IOsCategoryService;
import com.pussinboots.morning.cms.modules.system.category.vo.OsCategoryRecursion;
import com.pussinboots.morning.cms.modules.system.product.entity.OsProductCategory;
import com.pussinboots.morning.cms.modules.system.product.service.IOsProductCategoryService;
import com.pussinboots.morning.common.controller.BaseController;

/**
 * 
* 项目名称：morning-cms-webapp   
* 类名称：SystemVersionLogControlller   
* 类描述：版本日至表示层控制器    
* 创建人：陈星星   
* 创建时间：2017年2月17日 上午12:32:07
 */
@Controller
@RequestMapping(value = "/system/goods")
public class GoodsListCategoryControlller extends BaseController {
	
	
	/** 管理员列表 */
	private static final String SYSTEM_GOODS_LIST_SET_CATEGORY = getViewPath("modules/goods/system_goods_list_set_category");
	
	
	@Autowired
	private IOsCategoryService categoryService;
	
	@Autowired
	private IOsProductCategoryService productCategoryService;
	
	
	/**
	 * GET 跳转道商品分类页面
	 * @return
	 */
	//@RequiresPermissions("system:goods:list:add")
	@GetMapping(value = "/list/add/setCategory/{id}")
	public String toSetCategory(Model model,@PathVariable("id") Long productId ) {
		//获取当前产品分类
		OsCategory category = productCategoryService.queryCategoryOfProductByPid(productId);
		if(category!=null){
			//编辑
			OsCategoryRecursion ocr = new OsCategoryRecursion();
			ocr.setCategory(category);
			//获取全部分类
			List<OsCategory> allCategory = categoryService.selectByMap(null);
			//获取所有父分类
			//ocr = getParent(allCategory , ocr);
			//获取父分类字符串
			StringBuffer nameStr= new StringBuffer();
			getParentList(allCategory,category,nameStr);
			//设置返回值
			
			String str = ""
						+"<div style='font-weight:bold;font-size:14px;padding-left:20px;color:blue'>原属分类:</div>"
			        	+"<div style='font-weight:bold;font-size:14px;padding-left:20px;color:red'>"
			        	+ nameStr
			        	+"	<input type='hidden' name='categoryId' value='"+category.getCategoryId()+"'>"
			       		+"</div>";
			
			model.addAttribute("category", str);
			model.addAttribute("productId", productId);
		}else{
			//新增
			model.addAttribute("productId", productId);
		}
		return SYSTEM_GOODS_LIST_SET_CATEGORY;
	}
	
	//获取父分类
	private OsCategoryRecursion getParent(List<OsCategory> allCategory , OsCategoryRecursion ocr){
		OsCategory category = ocr.getCategory();
		Long pId = category.getParentId();
		for(OsCategory os : allCategory){
			Long aCid = os.getCategoryId();
			//父
			if(aCid == pId){
				OsCategoryRecursion oscr = new OsCategoryRecursion();
				oscr.setCategory(os);
				ocr.setParent(oscr);
			}
		}
		OsCategoryRecursion p = ocr.getParent();
		if(p!=null){
			getParent(allCategory,p);
		}
		return ocr;
	}
	
	//获取父分类
	private void getParentList(List<OsCategory> allCategory , OsCategory category, StringBuffer nameStr){
		Long pId = category.getParentId();
		for(OsCategory os : allCategory){
			Long aCid = os.getCategoryId();
			//父
			if(aCid == pId){
				nameStr.insert(0, "<span value='"+os.getCategoryId()+"'>"+os.getName()+"/&nbsp;</span>");
				System.out.println(nameStr);
				getParentList(allCategory,os,nameStr);
			}
		}
	}
	
	
	/**
	 * GET 获取商品分类目录
	 * @return
	 */
	//@RequiresPermissions("system:goods:list:add")
	@PostMapping(value = "/list/add/selectCategory",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public List<OsCategory> queryCategoryPost(Model model,String productId) {
		EntityWrapper<OsCategory> wrapper = new EntityWrapper<OsCategory>();
		wrapper.where("parent_id={0}", Long.valueOf(productId));
		List<OsCategory> list = categoryService.selectList(wrapper);
		return list;
	}
	
	/**
	 * GET 给产品设置分类
	 * @return
	 */
	//@RequiresPermissions("system:goods:list:add")
	@PostMapping(value = "/list/add/category",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public ResultBean addCategoryPost(Model model, @RequestBody JSONObject jsonParam) {
		
		ResultBean result = new ResultBean();
		
		String userName = null;
		Long productId = null;
		Long categoryId = null;
		AuthorizingUser authorizingUser = SingletonLoginUtils.getUser();
		if(authorizingUser!=null){
			userName = authorizingUser.getLoginName();
		}else{
			result.setCode(0);
			result.setSuccess(false);
			result.setMessage("未登录或登陆超时，请重新登陆");
		}
		
		if(jsonParam.containsKey("productId") && jsonParam.containsKey("categoryId")){
			productId = jsonParam.getLong("productId");
			categoryId = jsonParam.getLong("categoryId");
			
			OsProductCategory entity = new OsProductCategory();
			entity.setCategoryId(categoryId);
			entity.setProductId(productId);
			entity.setCreateBy(userName);
			Date createTime = new Date();
			entity.setCreateTime(createTime);
			
			Wrapper<OsProductCategory> wrapper = new EntityWrapper<>();
			wrapper.where("product_id={0}", productId);
			
			OsProductCategory p = productCategoryService.selectOne(wrapper);
			if(p!=null){
				entity.setProductCategoryId(p.getProductCategoryId()); 
			}
			
			productCategoryService.insertOrUpdate(entity);
			
			result.setCode(1);
			result.setSuccess(true);
			result.setMessage("添加成功");
		}else{
			result.setCode(0);
			result.setSuccess(false);
			result.setMessage("关联分类错误，未正确获取分类编号");
		}
		
		return result;
	}
	
	
}
